using System;

namespace Beetle.Protocol;

public abstract class EofPackage : Package
{
	private new class a
	{
		private int m_a;

		private byte[] b;

		private int c;

		public a(byte[] A_0)
		{
			b = A_0;
			this.m_a = A_0.Length - 1;
		}

		public bool a(byte A_0)
		{
			if (A_0 == b[c])
			{
				if (c == this.m_a)
				{
					return true;
				}
				c++;
			}
			return false;
		}

		public void a()
		{
			c = 0;
		}
	}

	public static byte[] DEFAULT_EOF = new byte[5] { 0, 13, 10, 13, 10 };

	private new bool m_a;

	private new ReadObjectInfo b = new ReadObjectInfo();

	private a c;

	public virtual byte[] EofData => DEFAULT_EOF;

	public EofPackage()
	{
		c = new a(EofData);
	}

	public EofPackage(IChannel channel)
		: base(channel)
	{
		c = new a(EofData);
	}

	public override void Import(byte[] data, int start, int count)
	{
		while (count > 0)
		{
			if (!this.m_a)
			{
				((x)Writer).Reset();
				c.a();
				this.m_a = true;
			}
			if (Writer.Length > TcpUtils.DataPacketMaxLength)
			{
				throw NetTcpException.DataOverflow();
			}
			if (a(data, ref start, ref count))
			{
				if (count > 0)
				{
					BufferOffset = start;
					BufferCount = count;
				}
				else
				{
					BufferOffset = 0;
					BufferCount = 0;
				}
				this.m_a = false;
				Writer.Position = 0L;
				OnMessageDataReader(Writer);
			}
		}
	}

	private bool a(byte[] A_0, ref int A_1, ref int A_2)
	{
		bool flag = false;
		int num = A_2;
		int offset = A_1;
		int num2 = 0;
		for (int i = 0; i < num; i++)
		{
			flag = c.a(A_0[A_1]);
			num2++;
			A_1++;
			A_2--;
			if (flag)
			{
				break;
			}
		}
		Writer.Write(A_0, offset, num2);
		return flag;
	}

	protected override void OnDisposed()
	{
		b = null;
		c = null;
		base.OnDisposed();
	}

	public override IMessage MessageRead(IDataReader reader)
	{
		IMessage message = ReadMessageByType(reader, b);
		if (message == null)
		{
			throw NetTcpException.TypeNotFound(b.ToString());
		}
		try
		{
			message.Load(reader);
			return message;
		}
		catch (Exception innerexception)
		{
			NetTcpException ex = NetTcpException.ObjectLoadError(b.ToString(), innerexception);
			throw ex;
		}
	}

	protected abstract IMessage ReadMessageByType(IDataReader reader, ReadObjectInfo typeTag);

	protected abstract void WriteMessageType(IMessage msg, IDataWriter writer);

	public override void MessageWrite(IMessage msg, IDataWriter writer)
	{
		WriteMessageType(msg, writer);
		msg.Save(writer);
		writer.Write(EofData, 0, EofData.Length);
	}
}
